package logic

import (
	"camera/C/Rpc/camera"
	"camera/C/Rpc/internal/svc"
	"camera/C/Rpc/model/mysql"
	"camera/C/Rpc/pkg"
	"context"
	"fmt"
	"github.com/google/uuid"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订单支付
func (l *OrderAddLogic) OrderAdd(in *camera.OrderAddRequest) (*camera.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Good{}
	err := g.GetOrderG(int(in.GoodId))
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if g.GoodStock <= int(in.Num) {
		return nil, fmt.Errorf("商品库存呢不足")
	}
	newString := uuid.NewString()
	o := mysql.Order{
		UserId:      g.UserId,
		GoodId:      int(in.GoodId),
		OrderSn:     newString,
		Amount:      g.GoodPrice * float64(in.Num),
		GoodTitle:   g.GoodTitle,
		GoodImage:   g.GoodImage,
		OrderStatus: int(in.OrderStatus),
		Payment:     2,
	}
	err = o.Create()
	if err != nil {
		return nil, fmt.Errorf("添加失败")
	}
	float := strconv.FormatFloat(g.GoodPrice*float64(in.Num), 'f', 2, 64)
	pay := pkg.NewAliPay()
	lip := pay.ALip(g.GoodTitle, newString, float)
	return &camera.OrderAddResponse{
		OrderSn: newString,
		Key:     lip,
	}, nil
}
